<!-- 年规 - 经营规划 - 新增/编辑 -->
<template>
  <view>
    <view class="px-3.75 pb-25">
      <view class="flex justify-between items-center text-28 c-#999">
        <view>币种：{{ currencyName }}</view>
        <view @click="onChargeUserClick">
          <text>负责人：</text>
          <text class="c-primary">{{ formData.chargeUser?.nickname || '待添加' }}</text>
        </view>
      </view>
      <view v-for="(item, index) in formData.list" :key="index">
        <view class="py-3 text-40 c-#333 font-600">{{ item.label }}</view>
        <view v-for="(child, childIndex) in item.list" :key="childIndex">
          <template v-if="child.list?.length > 0">
            <view class="py-2 text-28 c-#333">{{ child.year }}年</view>
            <view class="grid grid-cols-2 gap-2">
              <view v-for="(formItem, formIndex) in child.list" :key="formIndex" class="card-grey">
                <view class="flex-shrink-0 w-124">{{ formItem.label }}</view>
                <u-input v-model="formItem.value" class="flex-1" placeholder="请输入" :type="formItem.type"
                  :customStyle="{ fontSize: '28rpx' }" />
              </view>
            </view>
          </template>
          <template v-else>
            <view class="card-grey">
              <view class="flex-shrink-0 w-124">{{ child.year }}年</view>
              <u-input v-model="child.value" class="flex-1" placeholder="请输入" :type="child.type"
                :customStyle="{ fontSize: '28rpx' }" />
            </view>
          </template>
        </view>
      </view>
    </view>
    <view class="bottom-wrap-16 px-3.75 bg-white" @click="onSubmit">
      <view class="btn-primary">保存</view>
    </view>
  </view>
</template>
<script setup>
import { numFormat } from '@/common/util/format'
import { showToast, navigate } from '@/common/util/uni';
import { postBusinessPlanAdd } from '@/common/http/module/plan.js'

import { usePlanStore } from '@/store/plan'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
const planStore = usePlanStore()

const emit = defineEmits(['confirm'])
const props = defineProps({
  data: Object
})

const formData = reactive({
  chargeUser: '',
  list: [
    {
      label: '销售目标（万）',
      list: []
    },
    {
      label: '利润目标（万）',
      list: []
    },
    // {
    //   label: '利润率目标（万）',
    //   list: []
    // },
    {
      label: '新客户目标（人）',
      list: []
    },
    {
      label: '老客户目标（人）',
      list: []
    },
    {
      label: '企业规模',
      list: []
    },
    {
      label: '营销规划投入（万）',
      list: []
    }
  ]
})

const currencyName = computed(() => planStore.currency?.label || '未添加')

watch(() => props.data, (val) => initFormData(val))

function initFormData(data) {
  console.log('initFormData', data);
  if (!data || data.plan?.length == 0) {
    initDefaultFormData()
    return
  }

  formData.chargeUser = data.business_planning
  formData.list[0].list = data.plan.map(item => {
    return { year: item.year, value: item.sales_target > 0 ? numFormat(item.sales_target): '', type: 'digit' }
  })
  formData.list[1].list = data.plan.map(item => {
    return { year: item.year, value: item.profit_target > 0 ? numFormat(item.profit_target): '', type: 'digit' }
  })
  // formData.list[2].list = data.plan.map(item => {
  //   return { year: item.year, value: item.profit_rate_target > 0 ? numFormat(item.profit_rate_target): '', type: 'digit' }
  // })
  formData.list[2].list = data.plan.map(item => {
    return { year: item.year, value: item.new_customer_target > 0 ? numFormat(item.new_customer_target): '', type: 'digit' }
  })
  formData.list[3].list = data.plan.map(item => {
    return { year: item.year, value: item.old_customer_target > 0 ? numFormat(item.old_customer_target): '', type: 'digit' }
  })
  formData.list[4].list = data.plan.map(item => {
    return {
      year: item.year,
      list: [
        { label: '人数', value: item.company_person > 0 ? numFormat(item.company_person): '', type: 'number' },
        { label: '面积', value: item.company_area > 0 ? numFormat(item.company_area): '', type: 'digit' },
      ]
    }
  })
  formData.list[5].list = data.plan.map(item => {
    return {
      year: item.year,
      list: [
        { label: '线上投入', value: numFormat(item.company_person), type: 'digit' },
        { label: '线下投入', value: numFormat(item.company_area), type: 'digit' },
      ]
    }
  })
}

function initDefaultFormData() {
  console.log('initDefaultFormData');
  const currentYear = new Date().getFullYear()
  const formItemList = []
  const scaleList = []
  const inputList = []

  for (let i = 0; i < 3; i++) {
    formItemList.push({
      year: currentYear + i,
      value: '',
      type: 'digit'
    })
    scaleList.push({
      year: currentYear + i,
      list: [
        { label: '人数', value: '', type: 'number' },
        { label: '面积', value: '', type: 'digit' },
      ]
    })
    inputList.push({
      year: currentYear + i,
      list: [
        { label: '线上投入', value: '', type: 'digit' },
        { label: '线下投入', value: '', type: 'digit' },
      ]
    })
  }
  formData.list[0].list = JSON.parse(JSON.stringify(formItemList))
  formData.list[1].list = JSON.parse(JSON.stringify(formItemList))
  // formData.list[2].list = JSON.parse(JSON.stringify(formItemList))
  formData.list[2].list = JSON.parse(JSON.stringify(formItemList))
  formData.list[3].list = JSON.parse(JSON.stringify(formItemList))
  formData.list[4].list = scaleList
  formData.list[5].list = inputList
}

function onChargeUserClick() {
  const ids = formData.chargeUser?.user_id
  navigate(`/package_plan/pages/user/select?ids=${ids}&singleSelect=true`)
}

function onUserSelect(val) {
  formData.chargeUser = {
    user_id: val.user_id,
    nickname: val.user?.nickname
  }
}

function onSubmit() {
  console.log('onSubmit', formData);
  const currentYear = new Date().getFullYear()
  const planList = []
  for (let i = 0; i < 3; i++) {
    planList.push({
      year: currentYear + i,
      sales_target: formData.list[0].list[i].value,
      profit_target: formData.list[1].list[i].value,
      // profit_rate_target: formData.list[2].list[i].value,
      new_customer_target: formData.list[2].list[i].value,
      old_customer_target: formData.list[3].list[i].value,
      company_person: formData.list[4].list[i].list[0].value,
      company_area: formData.list[4].list[i].list[1].value,
      online_investment: formData.list[5].list[i].list[0].value,
      offline_investment: formData.list[5].list[i].list[1].value,
    })
  }

  const params = {
    club_id: userStore.currentSocietyId,
    year: planStore.year,
    business_planning_charge: formData.chargeUser?.user_id || formData.chargeUser?.id,
    plan: planList
  }

  postBusinessPlanAdd(params).then(() => {
    showToast('保存成功')
    emit('confirm')
  })
}

onMounted(() => initFormData(props.data))

defineExpose({ onUserSelect })
</script>

<style lang="scss" scoped>
.card-grey {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  padding: 0 20rpx;
  border-radius: 12rpx;
  background-color: #F6F6F6;
  font-size: 28rpx;
}
</style>
